package com.buba.springclould.controller;


import cn.hutool.json.JSONString;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buba.springcloud.dto.PaymentDto;
import com.buba.springcloud.pojo.CommonResult;
import com.buba.springcloud.pojo.Payment;
import com.buba.springcloud.utils.CopyProperties;
import com.buba.springcloud.utils.UniqueSeqUtil;
import com.buba.springclould.mapper.PaymentMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/*
 * 提供restful服务  供其他服务调用
 *
 * */
@RestController
@Slf4j
public class PaymentControler {

    @Autowired
    private PaymentMapper paymentMapper;
    //注入服务发现的注解
    @Autowired
    private DiscoveryClient discoveryClient;

    //获取服务信息
    @GetMapping("/payment/discovery")
    public  Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String s : services){
            log.info("********注册到eureka中的服务中有:"+services);
        }
        List <ServiceInstance> instances = discoveryClient.getInstances("MCROSERVICE-PAYMENT");
        for (ServiceInstance s: instances) {
            log.info("当前服务的实例有"+s.getServiceId()+"\t"+s.getHost()+"\t"+s.getPort()+"\t"+s.getUri());
        }
        return this.discoveryClient;
    }

    @CrossOrigin(methods = RequestMethod.POST)
    @PostMapping("/payment/create")
    @ResponseBody
    public CommonResult create(PaymentDto dept) throws InvocationTargetException, IllegalAccessException {
        //时间后端获取，区分用户和买家，在另一工程taodong-shop获取用户信息（userId）
        //生成订单序列
        UniqueSeqUtil.UniqueId uniqueId = UniqueSeqUtil.uniqueId(4);

        String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        dept.setCreateTime(createTime);
        Payment aPayment = new Payment();
        //该方式拷贝属性值，不同的值类型不能拷贝
        BeanUtils.copyProperties(dept,aPayment);
        aPayment.setPayAmount(Integer.parseInt(dept.getPayAmount()));
        aPayment.setOrderId(uniqueId.getId());
        int i = paymentMapper.insert(aPayment);
        log.info("***************插入成功*******"+i);
        if(i>0){
            return new CommonResult(200,"插入数据库成功",aPayment.getOrderId());
        }else{
            return new CommonResult(444,"插入数据库失败",null);
        }
    }
    @CrossOrigin(methods = RequestMethod.GET)
    @GetMapping("/payment/get/{id}")
    public CommonResult queryById(@PathVariable("id") String orderId){
        QueryWrapper<Payment> wrapper = new QueryWrapper<>();

//        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        wrapper.eq("order_id",orderId);
        Payment payment = paymentMapper.selectOne(wrapper);

        log.info("***************查询成功*********1"+payment);
        if(payment!=null){
            return new CommonResult(200,"查询成功",payment.getPaymentStatus());
        }else{
            return new CommonResult(444,"查询失败",null);
        }
    }


    @CrossOrigin(methods = RequestMethod.GET)
    @GetMapping("/payment/getList/{userId}")
    public CommonResult queryListByUserId(@PathVariable("userId") String userId){
        List<Payment> list = new ArrayList<>();
        List<PaymentDto> dtoList = new ArrayList<>();
        QueryWrapper<Payment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        list = paymentMapper.selectList(wrapper);
        if(list!=null){
            for(Payment payment: list){
                //需要new一个PaymentDto对象，不然后边会报target为空
                PaymentDto pamentDto = new PaymentDto();
                BeanUtils.copyProperties(payment,pamentDto);
                if(payment.getPaymentStatus()>0){
                    pamentDto.setPayStatusName("已付款");
                }else if(payment.getPayAmount()==0){
                    pamentDto.setPayStatusName("免费");
                }else{
                    pamentDto.setPayStatusName("未付款，收款确认中");
                }
//                pamentDto.setPayStatusName(payment.getPaymentStatus()==1?"已付款":"未付款");
                dtoList.add(pamentDto);
            }

//        DtoList = JSON.parseArray(JSON.toJSONString(list), PaymentDto.class);

            return new CommonResult(200,"查询成功",dtoList);
        }else{
            return new CommonResult(444,"查询失败",null);
        }
    }
}
